package com.njupt.service;

import com.njupt.dao.SysDeptMapper;
import com.njupt.exception.ParamException;
import com.njupt.model.SysDept;
import com.njupt.param.DeptParam;
import com.njupt.util.BeanValidator;
import com.njupt.util.LevelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    public void save(DeptParam deptParam){
        BeanValidator.check(deptParam);
        if(checkExist(deptParam.getParentId(),deptParam.getName(),deptParam.getId())){
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept dept = SysDept.builder().name(deptParam.getName()).parentId(deptParam.getParentId())
                        .seq(deptParam.getSeq()).remark(deptParam.getRemark()).build();
        dept.setLevel(LevelUtil.calculateLevel(getLevel(deptParam.getParentId()),deptParam.getParentId()));
        dept.setOperator("system");//TODO
        dept.setOperatorTime(new Date());
        dept.setOperatorIp("localhost");
        sysDeptMapper.insertSelective(dept);
    }

    private boolean checkExist(Integer parentId,String deptName,Integer deptId){
        //TODO
        return true;
    }

    private String getLevel(Integer deptId){
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if(dept == null){
            return null;
        }
        return dept.getLevel();
    }

    public void update(DeptParam deptParam) {

    }
}
